/**
 * Created by Administrator on 2017/4/13.
 */

function RoomManager() {
    this._users = { // uid => {}
        /*
         roomId: 0,      // 进入的房间号
         ownRoomId: 0,   // 创建的房卡型房间号
         */
    };

    this._rooms = { // roomId => {}
        /*
         gameType: "",   // 游戏类型
         subType: "",    // 子游戏类型
         users: []       // 房间内的uid

         creator: 0,     // 房卡场，房主uid

         scene: 0,       // 金币场，场景编号
         playerNum,      // 金币场，玩家上限
         updateTime:0,   // 金币场，更新时间

         matchId: 0,     // 比赛场
         */
    };

    this._gameScenes = {};  // 金币场房间列表 {$gameType:{$subType:{$scene:{}}}}

    this._creators = {  // 代开房间的记录
        /**
         * uid:[{
         * "rid": 房间号
         * "need" 房间消耗
         * }...]
         */
    }
}


RoomManager.prototype = {

    /**
     * 是否存在某房间
     * @param roomId
     */
    existRoom: function (roomId) {
        this._rooms.hasOwnProperty(roomId);
    },

    /**
     * 添加房卡场
     * @param gameType 游戏类型
     * @param subType 子游戏类型
     * @param creator 创建者uid
     * @returns {number} 房间号
     * @index {number} 房间的位置
     */
    addCardRoom: function (gameType, subType, creator, needResource, addOptions) {
        var roomId = gGlobalManager.allocCardRoomId();
        if (this.existRoom(roomId)) {
            return 0;
        }

        var room = {
            roomId: roomId,
            gameType: gameType,
            subType: subType,
            users: [],

            creator: creator,
        };

        if (addOptions && addOptions.agency) {
            this._addCreatRoom(creator, roomId, needResource, addOptions);
        } else {
            var user = this._getUserNew(creator);
            user.ownRoomId = roomId;
        }

        this._addRoom(room);
        return roomId;
    },

    /**
     * 添加金币场
     * @param gameType
     * @param subType
     * @param scene
     * @param playerNum
     * @returns {number} 房间号
     */
    addSceneRoom: function (gameType, subType, scene, playerNum) {
        var roomId = gGlobalManager.allocCoinRoomId();
        if (this.existRoom(roomId)) {
            return 0;
        }

        var room = {
            roomId: roomId,
            gameType: gameType,
            subType: subType,
            users: [],

            scene: scene,
            playerNum: playerNum,
            updateTime: Date.getStamp(),
        };

        this._addRoom(room);
        return roomId;
    },

    /**
     * 添加比赛场
     * @param gameType
     * @param subType
     * @param matchId
     * @returns {*}
     */
    addMatchRoom: function(gameType, subType, matchId) {
        var roomId = gGlobalManager.allocMatchRoomId(matchId);
        if (this.existRoom(roomId)) {
            return 0;
        }

        var room = {
            roomId: roomId,
            gameType: gameType,
            subType: subType,
            users: [],

            matchId: matchId,
        };

        this._addRoom(room);
        return roomId;
    },

    /**
     * 找一个未满的金币场房间
     * @param gameType
     * @param subType
     * @param scene
     */
    selectSceneRoom: function (gameType, subType, scene) {
        var rooms = this._getSceneRooms(gameType, subType, scene);
        if (!rooms) {
            return 0;
        }

        var selectRoomId = 0;
        ExObject.each(rooms, function (roomId, room) {
            if (room.users.length < room.playerNum) {
                selectRoomId = room.roomId;
                return false;
            }
        });

        return selectRoomId;
    },

    getSceneRooms: function (gameType, subType, scene) {
        return this._getSceneRooms(gameType, subType, scene);
    },

    delRoom: function (roomId) {
        var room = this._rooms[roomId];
        if (!room) {
            return false;
        }

        room.users.forEach(function (uid) {
            this._userQuitRoom(uid, roomId);
        }.bind(this));
        this._delCreatRoom(roomId);
        this._delRoom(room);
        return true;
    },

    getRoom: function (roomId) {
        return this._rooms[roomId];
    },

    userEnterRoom: function (uid, roomId) {
        if (Def.isMatchRoomId(roomId)) {

        }

        var room = this._rooms[roomId];
        if (!room) {
            return false;
        }

        var user = this._getUserNew(uid);
        user.roomId = roomId;
        room.users.remove(uid);
        room.users.push(uid);

        if (room.scene) {
            room.updateTime = Date.getStamp();
        }

        return true;
    },

    userQuitRoom: function (uid) {
        var user = this._users[uid];
        if (!user) {
            return false;
        }

        var roomId = user.roomId;
        var room = this._rooms[roomId];
        if (!room) {
            return false;
        }

        room.users.remove(uid);

        if (room.scene) {
            room.updateTime = Date.getStamp();
        }

        this._userQuitRoom(uid, roomId);

        return true;
    },

    getUserRoomId: function (uid) {
        var user = this._users[uid];
        if (!user) {
            return 0;
        }

        return user.roomId;
    },

    getUser: function (uid) {
        return this._users[uid] || clone(this._newUser());
    },

    _getUserNew: function (uid) {
        var user = this._users[uid];
        if (!user) {
            user = clone(this._newUser());
            this._users[uid] = user;
        }
        return user;
    },

    _newUser: function () {
        return {
            roomId: 0,
            ownRoomId: 0,
        }
    },

    _userQuitRoom: function (uid, roomId) {
        var user = this._users[uid];
        if (!user) {
            return;
        }

        if (user.roomId == roomId) {
            user.roomId = 0;
        }

        if (user.ownRoomId == roomId) {
            user.ownRoomId = 0;
        }

        if (!user.roomId && !user.ownRoomId) {
            delete this._users[uid];
        }

        gPlayerManger.getPlayer(uid, function (player) {
            if (!player) {
                return;
            }

            if (player.isRobot()) {
                gRobotManager.freeUser(uid);
            }
        });
    },

    _addRoom: function (room) {
        this._rooms[room.roomId] = room;

        if (room.scene) {
            this._addSceneRoom(room);
        }
    },

    _delRoom: function (room) {
        delete this._rooms[room.roomId];

        if (room.scene) {
            this._delSceneRoom(room);
        }
    },

    _addSceneRoom: function(room) {
        if (!room.scene) {
            return;
        }

        var gameRooms = this._gameScenes[room.gameType];
        if (!gameRooms) {
            gameRooms = {};
            this._gameScenes[room.gameType] = gameRooms;
        }

        var subRooms = gameRooms[room.subType];
        if (!subRooms) {
            subRooms = {};
            gameRooms[room.subType] = subRooms;
        }

        var sceneRooms = subRooms[room.scene];
        if (!sceneRooms) {
            sceneRooms = {};
            subRooms[room.scene] = sceneRooms;
        }

        sceneRooms[room.roomId] = room;
    },

    _delSceneRoom: function(room) {
        if (!room.scene) {
            return;
        }

        var gameRooms = this._gameScenes[room.gameType];
        if (!gameRooms) {
            return;
        }

        var subRooms = gameRooms[room.subType];
        if (!subRooms) {
            return;
        }

        var sceneRooms = subRooms[room.scene];
        if (!sceneRooms) {
            return;
        }

        delete sceneRooms[room.roomId];
    },

    _getSceneRooms: function (gameType, subType, scene) {
        var gameRooms = this._gameScenes[gameType];
        if (!gameRooms) {
            return;
        }

        var subRooms = gameRooms[subType];
        if (!subRooms) {
            return;
        }

        return subRooms[scene];
    },

    /**
     *
     */
    _addCreatRoom: function (uid, rid, needResource, addOptions) {
        var info = {
            "rid": rid,
            "need": needResource
        };
        if (addOptions && addOptions.index){
            info["index"] = addOptions.index;
        }
        if (this._creators[uid]) {
            this._creators[uid].push(info);
        } else {
            this._creators[uid] = [info];
        }
    },

    _delCreatRoomCreator: function (uid) {
        delete this._creators[uid];
    },
    /**
     * 删除一个创建的房间
     */
    _delCreatRoom: function (rid) {
        console.log("deleleltetl")
        var users = Object.keys(this._creators);
        for (var i = 0; i < users.length; ++i) {
            var len = this._creators[users[i]].length;
            this._creators[users[i]] = this._creators[users[i]].filter(function (v) {
                return v['rid'] != rid;
            });
            if (len != this._creators[users[i]].length) {
                if (this._creators[users[i]].length == 0) {
                    delete this._creators[users[i]];
                    return;
                }
                return;
            }
        }
        ;
    },
    /**
     * 查找玩家创建的房间
     * @return [rid...]
     */
    queryCreatRooms: function (uid) {
        if (this._creators[uid]) {
            return this._creators[uid];
        }
        return [];
    }
}

module.exports = new RoomManager();